﻿using System.Text.RegularExpressions;
using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Core.Helpers
{
    public static class WebBrowser
    {
        private const string browserPattern = "^Mozilla/4.0 \\(compatible; (?<Browser>MSIE) (?<Version>[0-9\\.]+); .*\\)|^Mozilla/5.0 \\((?<Browser>SymbianOS)\\/(?<Version>[0-9\\.]+);.*\\)|^Mozilla/5.0 \\(.*\\)\\sGecko.*(?<Browser>Firefox)/(?<Version>[0-9\\.]+)|(?<Browser>Opera).*\\(.*\\sVersion.(?<Version>[0-9\\.]+)|^Mozilla.*\\((?<Browser>iPhone).*Version.(?<Version>[0-9\\.]+)|Mozilla.*(?<Browser>Chrome).(?<Version>[0-9\\.]+)|Mozilla.*(?<Browser>Konqueror).(?<Version>[0-9\\.]+)|Mozilla.*(?<Browser>SeaMonkey).(?<Version>[0-9\\.]+)|Mozilla.*(?<Browser>Camino).(?<Version>[0-9\\.]+)|Mozilla.*(?<Browser>Chimera).(?<Version>[0-9\\.]+)|Opera.*(?<Browser>Opera Mini).(?<Version>[0-9\\.]+)|(?<Browser>Opera).(?<Version>[0-9\\.]+).\\(.*|Mozilla.*(?<Browser>Safari).(?<Version>[0-9\\.]+)";


        public static string GetBrowserName()
        {
            string browsername = HttpContext.Current.Request.Browser.Browser;
            MatchCollection m = MatchUserAgent();

            if (m == null) { return browsername; }

            if (m.Count > 0)
            {
                browsername = m[0].Groups["Browser"].Value;
            }

            if (browsername == "IE") { browsername = "MSIE"; }

            return browsername;
        }

        public static string GetBrowserVersion()
        {
            string browserversion = HttpContext.Current.Request.Browser.Version;
            MatchCollection m = MatchUserAgent();

            if (m == null) { return browserversion; }

            if (m[0].Groups["Version"].Value != null) { browserversion = m[0].Groups["Version"].Value; }

            return browserversion;
        }

        private static MatchCollection MatchUserAgent()
        {
            string ua = HttpContext.Current.Request.UserAgent;
            //throw new Exception(ua);
            if (Regex.IsMatch(ua, browserPattern, RegexOptions.IgnoreCase))
            {
                MatchCollection m = Regex.Matches(ua, browserPattern, RegexOptions.IgnoreCase);
                return m;
            }
            return null;
        }

        public static string GetLanguages()
        {
            StringBuilder sb = new StringBuilder();

            foreach (string s in HttpContext.Current.Request.UserLanguages)
            {
                if (sb.Length > 0) { sb.Append(","); }
                sb.Append(s);
            }

            return sb.ToString();
        }


    }
}
